import {MetricsPanelCtrl, alertTab} from 'app/plugins/sdk';
import _ from 'lodash';
import kbn from 'app/core/utils/kbn';

import echarts from 'echarts';
import './libs/dark';
import './style.css!';

export class Controller extends MetricsPanelCtrl {

    constructor($scope, $injector) {
        super($scope, $injector);
        this.logScales = {
            '对数（底数 2）': 2,
            '对数（底数 10）': 10,
            '对数（底数 32）': 32,
            '对数（底数 1024）': 1024,
        };
        this.yAxisType = {
            'value': '数值轴',
            'log': '对数轴'
        };
        console.log(this);
        // var min = _.isUndefined(this.range.from) ? null : this.range.from.valueOf();
        // var max = _.isUndefined(this.range.to) ? null : this.range.to.valueOf();
        // var min = null, max =null;
        // console.log(max, min);
        this.xAxis = {
            show: true,
            type: 'time',
            axisLabel: {
                inside: false,
                textStyle: {
                    color: '#fff'
                }
            },
            axisTick: {
                show: false
            },
            axisLine: {
                show: false
            },
            lineBreak: false,
            lineNumber: 10,
            z: 10
        };
        this.yAxis = [
            {
                name: null,
                show: true,
                logBase: 1,
                min: null,
                max: null,
                format: 'short',
                type: 'value',
                axisLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    show: true,
                    textStyle: {
                         color: '#fff'
                    },
                },
            },{
                name: null,
                show: true,
                logBase: 1,
                min: null,
                max: null,
                format: 'short',
                type: 'value',
                axisLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    show: true,
                    textStyle: {
                        color: '#fff'
                    },
                },
            }
        ];
        this.series = [];
        const panelDefaults = {
            xAxis: this.xAxis,
            yAxis: this.yAxis,
            legend: {
                show: true,
            },
            smooth: false
        };

        _.defaults(this.panel, panelDefaults);

        this.unitFormats = kbn.getUnitFormats();

        for (let i = 0; i < this.panel.yAxis.length; i++) {
            this.setUnitFormat(this.panel.yAxis[i], {value: this.panel.yAxis[i].format});
        }
        this.setXAxisLabel();
        this.events.on('data-received', this.onDataReceived.bind(this));
        this.events.on('data-error', this.onDataError.bind(this));
        this.events.on('data-snapshot-load', this.onDataReceived.bind(this));
        this.events.on('init-edit-mode', this.onInitEditMode.bind(this));
        this.events.on('panel-initialized', this.render.bind(this));
    }

    onDataReceived(dataList) {
        var seriesData = [];
        var self = this;

        if (this.series.length === 0){
            _.forEach(dataList, function (row) {
                var series = {
                    type: 'line',
                    name: row.target,
                    smooth: self.panel.smooth,
                    symbolSize: 1,
                    data: []
                };
                _.forEach(row.datapoints, function (datapoint) {
                    var date = new Date(datapoint[1]);
                    series.data.push({
                        name: date.toString() ,
                        value:[
                            datapoint[1],
                            datapoint[0]
                        ]
                    });
                });
                seriesData.push(series);
            });
            this.series = seriesData;
            this.refreshPanel();
        } else {
            _.forEach(dataList, function (row) {
                for (let i = 0; i < self.series.length; i++) {
                    if(self.series[i].name === row.target){
                        for (let j = 0; j < row.datapoints.length; j++) {
                            var datapoint = row.datapoints[j];
                            var date = new Date(datapoint[1]);
                            self.series[i].data.shift();
                            self.series[i].data.push({
                                name: date.toString() ,
                                value:[
                                    datapoint[1],
                                    datapoint[0]
                                ]
                            });
                        }
                    }
                }
            });
            this.myChart.setOption({series: this.series});
        }
    }

    onDataError(err) {
        this.render();
    }

    onInitEditMode() {
        this.addEditorTab('数轴', 'public/plugins/atlasdata-echarts-line-panel/partials/axes_editor.html', 2);
        this.addEditorTab('显示', 'public/plugins/atlasdata-echarts-line-panel/partials/tab_display.html', 3);
        this.subTabIndex = 0;
    }

    setUnitFormat(axis, subItem) {
        axis.format = subItem.value;
        axis.axisLabel.formatter = function(value) {
            try {
                return subItem.value !== 'none' ? kbn.valueFormats[subItem.value](value, axis.decimals, 0) : value;
            } catch (err) {
                console.error(err.message || err);
                return value;
            }
        };
        this.refreshPanel();
    }

    refreshPanel(){
        this.refreshed = true;
        this.render();
        this.refreshed = false;
    }

    setXAxisLabel(){
        if(this.panel.xAxis.lineBreak && !isNaN(this.panel.xAxis.lineNumber) && this.panel.xAxis.lineNumber > 0){
            let lineNumber = this.panel.xAxis.lineNumber;
            this.panel.xAxis.axisLabel.formatter = function(value) {
                if (value.length > lineNumber){
                    let n = Math.floor(value.length/lineNumber);
                    var format = '';
                    for (var i = 0;i <= n; i++) {
                        format += value.substr(i* lineNumber, lineNumber) + '\n';
                    }
                    return format;
                }
                return value;
            };
        } else {
            this.panel.xAxis.axisLabel.formatter = null;
        }
        this.refreshPanel();
    }

    setSmooth(){
        for (var i = 0; i < this.series.length; i++) {
            this.series[i].smooth = this.panel.smooth;
        }
        this.refreshPanel();
    }

    getPanelPath() {
        // the system loader preprends publib to the url, add a .. to go back one level
        return '../' + grafanaBootData.settings.panels[this.pluginId].baseUrl + '/';
    }

    link(scope, elem, attrs, ctrl) {
        const $panelContainer = elem.find('.echarts_container')[0];
        let option = {};

        ctrl.refreshed = true;

        function setHeight() {
            let height = ctrl.height || panel.height || ctrl.row.height;
            if (_.isString(height)) {
                height = parseInt(height.replace('px', ''), 10);
            }

            $panelContainer.style.height = height + 'px';
        }

        setHeight();

        ctrl.myChart = echarts.init($panelContainer, 'dark');

        setTimeout(function () {
            ctrl.myChart.resize();
        }, 1000);

        function render() {

            if (!ctrl.myChart) {
                return;
            }
            var panelWidth = elem.width();

            setHeight();
            ctrl.myChart.resize();
            console.log(ctrl);
            var min = _.isUndefined(ctrl.range) ? null : ctrl.range.from.valueOf();
            var max = _.isUndefined(ctrl.range) ? null : ctrl.range.to.valueOf();
            ctrl.panel.xAxis.max = max;
            ctrl.panel.xAxis.min = min;
            var ticks = panelWidth / 100;
            // ctrl.panel.xAxis.splitNumber = ticks;
            ctrl.panel.xAxis.axisLabel.formatter = function(value){
                var date= new Date(value);
                if (min && max && ticks) {
                    var range = max - min;
                    var secPerTick = range / ticks / 1000;
                    var oneDay = 86400000;
                    var oneYear = 31536000000;

                    if (secPerTick <= 45) {
                        return date.getHours() + ':' + date.getMinutes() + ':'+ date.getSeconds();
                    }
                    if (secPerTick <= 7200 || range <= oneDay) {
                        return date.getHours() + ':' + date.getMinutes();
                    }
                    if (secPerTick <= 80000) {
                        return (date.getMonth()+1) + '/' + date.getDay() +' ' +date.getHours() + ':' + date.getMinutes();
                    }
                    if (secPerTick <= 2419200 || range <= oneYear) {
                        return (date.getMonth()+1) + '/' + date.getDay();
                    }

                    return date.getFullYear() + '-' + (date.getMonth()+1);
                }

                return date.getHours() + ':' + date.getMinutes() ;
            };
            if (ctrl.refreshed) {
                ctrl.myChart.clear();
                option = {
                    tooltip:{ show: true},
                    legend: ctrl.panel.legend,
                    xAxis: ctrl.panel.xAxis,
                    yAxis: ctrl.panel.yAxis,
                    series: ctrl.series
                };
                ctrl.myChart.setOption(option);
            }
        }

        function time_format(ticks, min, max) {
            console.log(ticks,min,max);
            if (min && max && ticks) {
                var range = max - min;
                var secPerTick = range / ticks / 1000;
                var oneDay = 86400000;
                var oneYear = 31536000000;

                if (secPerTick <= 45) {
                    return '%H:%M:%S';
                }
                if (secPerTick <= 7200 || range <= oneDay) {
                    return '%H:%M';
                }
                if (secPerTick <= 80000) {
                    return '%m/%d %H:%M';
                }
                if (secPerTick <= 2419200 || range <= oneYear) {
                    return '%m/%d';
                }
                return '%Y-%m';
            }

            return '%H:%M';
        }

        this.events.on('render', function () {
            render();
            ctrl.renderingCompleted();
        });
    }
}

Controller.templateUrl = 'partials/module.html';
